package pl.uz.zgora.plan;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.text.DateFormatSymbols;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class HelperMethodsManager {
	private static final String[] dayNames = getFixedDayNames(); 
	
	public static String[] getFixedDayNames() {
		String[] dayNames = new DateFormatSymbols(new Locale("pl")).getWeekdays();
		ArrayList<String> dayNamesFixed = new ArrayList<String>();
		for(String day: dayNames) {
			if(!day.equals("")) {
				dayNamesFixed.add(day.substring(0,1).toUpperCase() + day.substring(1).toLowerCase());
			}
		}
		
		dayNames = new String[dayNamesFixed.size()];
		dayNamesFixed.toArray(dayNames);
		return dayNames;
	}
	
	public static void goToUrl (final String url, final Activity activity) {
        Uri uriUrl = Uri.parse(url);
        Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
        activity.startActivity(launchBrowser);
    }

	
	public static boolean isEmpty(final String value) {
		if(value == null || value.equals("")) {
			return true;
		}
		return false;
	}
	
	public static String getStackTrace(Throwable aThrowable) {
		final Writer result = new StringWriter();
		final PrintWriter printWriter = new PrintWriter(result);
		aThrowable.printStackTrace(printWriter);
		return result.toString();
	}
	
	/**
	 * Zwraca nazwę wybranego dnia
	 * 
	 * @param dayNumber - numer dnia
	 * @return
	 * Nazwa dnia
	 */
	public static String getDayName(final Integer dayNumber) {
		// Funkcja Calendat.get(...) zwraca numery dni w formacie 1..7, konieczna jest konwersja do 0..6
		String dayName = dayNames[dayNumber - 1];
		return dayName;
	}
	
	/**
	 * Funkcja zwraca nazwę obecnego dnia
	 * @return
	 * Nazwa dnia
	 */
	public static String getTodayDayName() {
		Calendar calendar = Calendar.getInstance();
		final Integer dayNumber = calendar.get(Calendar.DAY_OF_WEEK);
		return getDayName(dayNumber);
	}
	
	/**
	 * Funkcja wyświetla komunikat o przyczynie i rodzaju wyjątku
	 * 
	 * @param METHOD_NAME - nazwa funkcji, w której został wykryty wyjątek
	 * @param errorMsg - treść błędu
	 * @param appActivity - obiekt typu Activity
	 */
	public static void manageException(final String METHOD_NAME, final String errorMsg, final Activity appActivity) {
		manageException(METHOD_NAME, errorMsg, null, appActivity);
	}
	
	public static void manageException(final String METHOD_NAME, final String exteptionType, final String errorMsg,  final Activity appActivity) {
		if(appActivity != null) {
			final TextView tv = (TextView) appActivity.findViewById(R.id.tv_app_error);
			final LinearLayout layoutDownloadProgress = (LinearLayout) appActivity.findViewById(R.id.layoutDownloadProgress);
			tv.post(new Runnable() {

				public void run() {
					if(layoutDownloadProgress != null) {
						layoutDownloadProgress.setVisibility(View.GONE);
					}
					if(exteptionType != null) {
						tv.setText(Html.fromHtml("<b>Błąd:</b> " + "[" + exteptionType +  "]" + errorMsg));
					} else {
						tv.setText(Html.fromHtml("<b>Błąd:</b> " + errorMsg));
					}
					tv.append(Html.fromHtml("<br/><br/><b>Wywołana funkcja</b>:<br/>" + METHOD_NAME));
					tv.append(Html.fromHtml("<br/><br/><b>Proponowane rozwiązanie:</b><br/>Spróbuj ponownie później."));
					tv.append(Html.fromHtml("<br/><br/><b>Opis zdarzenia:</b><br/>Podczas pobierania danych z serwera wystąpił błąd. Może być to spowodane jego awarią lub brakiem połączenia z intenetem."));
					tv.setVisibility(View.VISIBLE);
				}
			});
		} else {
			throw new IllegalArgumentException("Nieprawidłowy argument: appActivity jest null'em");
		}
	}
	
	/**
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isOnline(final Context context) {
	    ConnectivityManager cm =
	        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

	    if(cm == null) { return false; }
	    final NetworkInfo networkInfo = cm.getActiveNetworkInfo();
	    
	    if(networkInfo == null) { return false; }
	    return cm.getActiveNetworkInfo().isConnectedOrConnecting();
	}
	
	// Pomocnicza funkcja sprawdzająca obecność aplikacji Mapy w telefonie
	private static boolean isAppInstalled(final String uri, final Context context) {
	    PackageManager pm = context.getPackageManager();
	    boolean app_installed = false;
	    try {
	        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
	        app_installed = true;
	    } catch (PackageManager.NameNotFoundException e) {
	        app_installed = false;
	    }
	    return app_installed;
	}
	/**
	 * 
	 * @param context
	 * @return
	 */
	public static ProgressDialog getProgressDialog(final Context context) {
		return getProgressDialog(context, "Pobieranie danych. Proszę czekać...");
	}
	
	public static ProgressDialog getProgressDialog(final Context context, final String msg) {
		ProgressDialog dialog = new ProgressDialog(context);
        dialog.setMessage(msg);
		dialog.setIndeterminate(true);
		return dialog;
	}
	
	public static AlertDialog getAlertDialog(final Context context, final Activity activity) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setMessage("Are you sure you want to exit?")
		       .setCancelable(false)
		       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   activity.finish();
		           }
		       })
		       .setNegativeButton("No", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
		AlertDialog alert = builder.create();
		return alert;
	}
	
	public static AlertDialog getErrorDialog(final Context context, final String msg, final Activity activity) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setMessage(msg)
		       .setCancelable(false)
		       .setNegativeButton("Ok", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.dismiss();
		                activity.finish();
		           }
		       });
		
		AlertDialog alert = builder.create();
		
		alert.setTitle("Błąd");
		return alert;
	}
	
	public static Dialog getConnectionErrorDialog(final Context context, final Activity activity) {
		final Dialog dialog = new Dialog(context);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		dialog.setContentView(R.layout.connection_error_dialog);
		
		TextView text = (TextView) dialog.findViewById(R.id.text);
		text.setText("Brak połączenia z internetem");
		
		Button okBtn = (Button) dialog.findViewById(R.id.conn_error_dialog_ok);
		okBtn.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				dialog.dismiss();
                activity.finish();
			}
		});
		
		Button settingsBtn = (Button) dialog.findViewById(R.id.conn_error_dialog_settings);
		settingsBtn.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				dialog.dismiss();
				Intent intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
				if(intent != null) {
					context.startActivity(intent);
				}
				activity.finish();
			}
		});
		
		dialog.setCancelable(false);
		
		return dialog;
	}
	
	public static void showToast(Context context,  String msg) {
		final int duration = Toast.LENGTH_SHORT;

		final Toast toast = Toast.makeText(context, msg, duration);
		toast.show();
	}
	
	public static void startGoogleMaps(final String address, final Activity activity) {
		Intent intent = new Intent(android.content.Intent.ACTION_VIEW, 
    			Uri.parse("http://maps.google.com/maps?daddr=" + address + ",+Zielona+G%C3%B3ra,+Polska&hl=pl&dirflg=r"));
    	if (isAppInstalled("com.google.android.apps.maps", activity)) {
    	    intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
    	}
    	activity.startActivity(intent);
	}
}
